package com.sscaipiao.android.activity;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;

import com.sscaipiao.android.R;
import com.sscaipiao.android.common.Constants;
import com.sscaipiao.android.model.User;
import com.sscaipiao.android.utils.UserDataServiceHelper;


public class LoadingActivity extends Activity {

	private ProgressDialog pBar = null;
	//private int newVerCode = 0;
	//private String newVerName = "";

	private String apkUrl = "";
	private String newVerCode = "";
	private String newVerName = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.loading_activity);

		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
				.detectDiskReads().detectDiskWrites().detectNetwork()
				.penaltyLog().build());
		StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
				.detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
				.penaltyLog().penaltyDeath().build());

		pBar = new ProgressDialog(this);
		SharedPreferences properties = null;
		Intent intent = null;

		String apkInfo = UserDataServiceHelper.getServerVerCode(LoadingActivity.this);
		String status = apkInfo.split(Constants.STRING_SPLITE_COMPLEX)[0];
		Log.v("status", status);
		if (apkInfo.isEmpty() || status.isEmpty()) {
			properties = getSharedPreferences("properties", 0);
			//Intent intent;
			if (properties == null || properties.getString("needGuide", "").equals("")) {
				intent = new Intent(LoadingActivity.this, GuideActivity.class);
			} else {
				intent = new Intent(LoadingActivity.this, LoginActivity.class);
			}

			Bundle b = new Bundle();
			intent.putExtras(b);
			startActivity(intent);
			return;
		}
		try {
			JSONObject jsonObject = new JSONObject(apkInfo.split(Constants.STRING_SPLITE_COMPLEX)[2]);
			apkUrl = jsonObject.getString("url");
			newVerCode = jsonObject.getString("versionCode");
			newVerName = jsonObject.getString("versionName");
			Log.v("newVerCode", newVerCode);

			if (Constants.LOGIN_SUCCESS_CODE.equals(status)) {
				int vercode = getVerCode(this); // 用到前面第一节写的方法
				Log.v("localVercode", vercode + "");
				if (Integer.parseInt(newVerCode) > vercode) {
					doNewVersionUpdate(); // 更新新版本

				}
				// notNewVersionShow(); // 提示当前为最新版本

				properties = getSharedPreferences("properties", 0);
				//Intent intent;
				if (properties == null || properties.getString("needGuide", "").equals("")) {
					intent = new Intent(LoadingActivity.this, GuideActivity.class);
				} else {
					intent = new Intent(LoadingActivity.this, LoginActivity.class);
				}

				Bundle b = new Bundle();
				intent.putExtras(b);
				startActivity(intent);


			}
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	private void notNewVersionShow() {
		int verCode = getVerCode(this);
		String verName = getVerName(this);
		StringBuffer sb = new StringBuffer();
		sb.append("当前版本:");
		sb.append(verName);
		sb.append(" Code:");
		sb.append(verCode);
		sb.append(",/n已是最新版,无需更新!");
		Dialog dialog = new AlertDialog.Builder(this).setTitle("软件更新")
				.setMessage(sb.toString())// 设置内容
				.setPositiveButton("确定",// 设置确定按钮
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
							                    int which) {
								// 结束应用
								// finish();
							}
						}).create();// 创建
		// 显示对话框
		dialog.show();
	}

	public static int getVerCode(Context context) {
		int verCode = -1;
		try {
			verCode = context.getPackageManager().getPackageInfo(
					Constants.app_package, 0).versionCode;
		} catch (NameNotFoundException e) {
			Log.e("getVerCode", e.getMessage());
		}
		return verCode;
	}


	private void doNewVersionUpdate() {
		int verCode = getVerCode(this);
		String verName = getVerName(this);
		StringBuffer sb = new StringBuffer();
		// sb.append("当前版本:");
		// sb.append(verName);
		// sb.append(" Code:");
		// sb.append(verCode);
		// sb.append(", 发现新版本:");
		// sb.append(newVerName);
		// sb.append(" Code:");
		// sb.append(newVerCode);
		sb.append("发现新版本");
		sb.append(", 是否更新?");
		Dialog dialog = new AlertDialog.Builder(this)
				.setTitle("软件更新")
				.setMessage(sb.toString())
						// 设置内容
				.setPositiveButton("更新",// 设置确定按钮
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
							                    int which) {

								pBar.setTitle("正在下载");
								pBar.setMessage("请稍候...");
								pBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
								downFile(apkUrl);
							}
						})
				.setNegativeButton("暂不更新",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
							                    int whichButton) {
								// 点击"取消"按钮之后退出程序
								// finish();
							}
						}).create();// 创建
		// 显示对话框
		dialog.show();
	}

	void downFile(final String url) {
		pBar.show();
		new Thread() {
			public void run() {
				HttpClient client = new DefaultHttpClient();
				HttpGet get = new HttpGet(url);
				HttpResponse response;
				try {
					response = client.execute(get);
					HttpEntity entity = response.getEntity();
					long length = entity.getContentLength();
					InputStream is = entity.getContent();
					FileOutputStream fileOutputStream = null;
					if (is != null) {
						File file = new File(
								Environment.getExternalStorageDirectory(),
								Constants.UPDATE_SAVENAME);
						if (file.exists()) {
							file.delete();
						}
						fileOutputStream = new FileOutputStream(file);
						byte[] buf = new byte[1024];
						int ch = -1;
						int count = 0;
						while ((ch = is.read(buf)) != -1) {
							fileOutputStream.write(buf, 0, ch);
							count += ch;
							if (length > 0) {
							}
						}
					}
					fileOutputStream.flush();
					if (fileOutputStream != null) {
						fileOutputStream.close();
					}
					down();
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}.start();
	}

	void down() {
		handler.post(new Runnable() {
			public void run() {
				pBar.cancel();
				update();
			}
		});
	}

	void update() {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(new File(Environment
				.getExternalStorageDirectory(), Constants.UPDATE_SAVENAME)),
				"application/vnd.android.package-archive");
		startActivity(intent);
	}


	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			Toast.makeText(LoadingActivity.this,
					(String) msg.obj,
					Toast.LENGTH_SHORT).show();
			finish();

		}
	};

	public static String getVerName(Context context) {
		String verName = "";
		try {
			verName = context.getPackageManager().getPackageInfo(
					Constants.app_package, 0).versionName;
		} catch (NameNotFoundException e) {
			Log.e("getVerName", e.getMessage());
		}
		return verName;
	}
}
